import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import * as svgCaptcha from 'svg-captcha';
import { v4 as uuidv4 } from 'uuid';
import { LoginDto } from './dto/login.dto';
import { CommonException } from '../../core/exception/common.exception';
import { JwtService } from '@nestjs/jwt';
import { SysUser } from '../user/entities/sys-user.entity';
import { ConfigService } from '@nestjs/config';
import { SysUserService } from '../sys-user/sys-user.service';
import { SysRoleService } from '../sys-role/sys-role.service';
import { SysMenuService } from '../sys-menu/sys-menu.service';
@Injectable()
export class AuthService {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private readonly sysUserService: SysUserService,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
    private readonly sysRoleService: SysRoleService,
    private readonly sysMenuService: SysMenuService,
  ) {}

  async logout(req) {
    return null;
  }

  // 获取信息
  async getInfo(req: any): Promise<any> {
    const userId = req.user.userId;
    const user = await this.sysUserService.getCurrentUser(userId);
    // 角色集合
    const roles = await this.sysRoleService.getRolePermission(user);
    // 权限集合
    const permissions = await this.sysRoleService.getMenuPermission(user);

    return {
      permissions,
      roles,
      user,
      msg: '操作成功',
      code: 200,
    };
  }

  async getRouters(userId: number): Promise<any> {
    const menus = await this.sysMenuService.selectMenuTreeByUserId(userId);
    return this.sysMenuService.buildMenus(menus);
  }

  // 获取验证码
  async getCaptchaImage(): Promise<any> {
    const captcha = svgCaptcha.create({
      size: 4,
      noise: 2,
      color: true,
      background: '#666',
      width: 112,
      height: 35,
    });
    const uuid = uuidv4();
    await this.cacheManager.set(`captcha:${uuid}`, captcha.text, 10);
    return {
      uuid,
      img: captcha.data,
      captchaEnabled: true,
    };
  }

  async login(data: LoginDto) {
    // 验证下验证码
    const captcha = await this.cacheManager.get(`captcha:${data.uuid}`);
    if (
      captcha.toString().toLowerCase() !== data.code.toString().toLowerCase()
    ) {
      throw new CommonException(500, '验证码失效');
    }
    // 检测账号密码
    const user: SysUser = await this.sysUserService.checkPassword(
      data.username,
      data.password,
    );
    const token = this.jwtService.sign(
      {
        userId: user.user_id,
        username: user.user_name,
      },
      {
        secret: this.configService.get('jwt.secret'),
      },
    );
    return {
      token,
    };
  }
}
